import { observable, action, autorun, toJS } from 'mobx';
import { WeaLocaleProvider } from 'ecCom';
import { throttleOfPart } from '../../util';

const getLabel = WeaLocaleProvider.getLabel;


import FileSystem from './fileSystem';
import PathSearch from './pathSearch';
import RightMenu from './rightMenu';
import PasteBoard from './pasteBoard';

class NetDisk {
   @observable fileSystem = new FileSystem(this); // 文件/文件夹相关
   @observable pathSearch = new PathSearch(this); // 路径、搜索栏相关
   @observable rightMenu = new RightMenu(this); // 右键菜单相关
   @observable pasteBoard = new PasteBoard(this); // 粘贴板相关

   /** ******   top组件相关   ******* */
   @observable topSelectedKey = 'netDisk';
   @action changeTopSelect = (v) => {
 this.topSelectedKey = v; 
};

   // 监控top组件的tab切换
   monitorTopSelection = autorun(() => {
      // 1.将选中清零 2.更新表格/图标的数据 3.path组件的homeTab切换 4.清空搜索
      if (this.topSelectedKey === 'netDisk') {
         // console.log('点击云盘');
      } else if (this.topSelectedKey === 'share') {
         // console.log('点击分享');
      }
      this.fileSystem.clearSelection(); // 选中清零
      this.pasteBoard.clearPasteBoard(); // 清空粘贴板
      this.pathSearch.updatePathHomTab(); // 更改homeTab
      this.fileSystem.setFileSystemData({ tableEdit: false, tableInputValue: '' }); // 清空搜索
   });


   /** ******   分享tab相关   ******* */
   @observable shareTabSelectedKey = 'myShare';
   // tab切换 1.选中清零 2.更新表格/图标数据 3.path组件的homeTab切换 4.清空搜索
   @action changeShareTabSelect = (v) => {
      this.shareTabSelectedKey = v;
      this.fileSystem.clearSelection(); // 清空选中
      this.pathSearch.updatePathHomTab(); // 更改homeTab
      this.fileSystem.setFileSystemData({ tableEdit: false, tableInputValue: '' }); // 清空搜索
   };


   /** ******   视图相关   ******* */
   @observable viewSettings = {
      type: 'icon', // 当前视图类型
      nowIcon: 'icon-coms-List',
      IconViewRef: null, // <DocFileIconView/> 组件的ref
   };

   // 改变视图类型 todo【！！需要重新请求table数据或data数据】
   @action changeView = (aim) => {
      let type;
      let nowIcon;
      if (aim === 'icon' || aim === 'list') {
         type = aim === 'list' ? 'list' : 'icon';
         nowIcon = type === 'list' ? 'icon-coms-Modular' : 'icon-coms-List';
      } else {
         type = this.viewSettings.type === 'list' ? 'icon' : 'list';
         nowIcon = this.viewSettings.type === 'list' ? 'icon-coms-List' : 'icon-coms-Modular';
      }
      this.viewSettings.type = type;
      this.viewSettings.nowIcon = nowIcon;
      this.fileSystem.clearSelection(); // 选中清零
      this.fileSystem.setFileSystemData({ tableEdit: false, tableInputValue: '' }); // 清空搜索
   };

   // 赋值ref
   @action setIconViewRef = (ref) => {
      this.viewSettings.IconViewRef = ref;
   };


   /** ******   操作按钮的disabled控制   ******* */
   @observable operationButtons = {
      download: true,
      share: true,
      publish: true,
      delete: true,
      cancelShare: true,
      save: true,

      open: true,
      paste: true,
      rename: true,
      seeShareTarget: true,
   };

   // 设置操作按钮的disabled状态
   @action handleButtons = (length, aim) => {
      // aim目标值
      let newBtns = { ...toJS(this.operationButtons) };

      // 针对文件夹的限制
      const multipleAndFolder = (newBtns) => {
         let key = this.fileSystem.tableStore.selectedRowKeys[0];
         let file,
result;
         this.viewSettings.type === 'icon' && (file = toJS(this.fileSystem.data).find(f => f.id === key));
         this.viewSettings.type === 'list' && (file = toJS(this.fileSystem.tableStore.datas).find(f => f.id === key));
         file.type === 'file' && (result = false);
         file.type !== 'file' && (result = true);
         return result;
      };

      // 判断是否在文件夹下
      const isInsideFolder = this.pathSearch.path.length !== 0;

      for (let i in toJS(this.operationButtons)) {
         if (Object.prototype.hasOwnProperty.call(this.operationButtons, i)) {
            switch (i) {
               case 'download': // 仅当选中一个文件，且类型为file时置为false，否则true
                  length === 1 && (newBtns[i] = multipleAndFolder(newBtns));
                  length > 1 && (newBtns[i] = true);
                  length < 1 && (newBtns[i] = true);
                  break;
               case 'open':
                  length === 1 && (newBtns[i] = aim);
                  length > 1 && (newBtns[i] = true);
                  break;
               case 'rename':
                  length === 1 && (newBtns[i] = aim);
                  length > 1 && (newBtns[i] = true);
                  break;
               case 'seeShareTarget':
                  if (!isInsideFolder) // 判断当前是否在文件夹下，如果不是
                  {
                     length === 1 && (newBtns[i] = aim);
                     length > 1 && (newBtns[i] = true);
                  }
                  isInsideFolder && (newBtns[i] = true);
                  break;
               case 'cancelShare':
                  isInsideFolder && (newBtns[i] = true);
                  !isInsideFolder && (newBtns[i] = aim);
                  break;
               case 'paste':
                  newBtns[i] = true;
                  const board = toJS(this.pasteBoard.pasteData);
                  const keys = Object.keys(board);
                  let path = toJS(this.pathSearch.path);
                  let currentFolderID = path.length > 0 ? path[path.length - 1].id : 'home';
                  // 合法 且 被选中文件不在当前目录 -> 允许粘贴
                  this.pasteBoard.checkPasteValid() && keys.length && (board[keys[0]].parentid !== currentFolderID) && (newBtns[i] = false);
                  break;
               default:
                  newBtns[i] = aim;
                  break;
            }
         }
      }
      return newBtns;
   };

   // 监控选中的Keys 1.按钮的disabled状态 2.右键菜单（1.更新数据源 2.更新disabled状态）
   selectChange = autorun(() => {
      // 按钮的disabled状态
      let length = this.fileSystem.tableStore.selectedRowKeys.length;
      length > 0 && (this.operationButtons = this.handleButtons(length, false));
      length === 0 && (this.operationButtons = this.handleButtons(length, true));
      // 更新右键菜单数据源
      this.rightMenu.updateRightMenuSource(length);
      // 更新当前右键菜单的 显隐和disabled状态
      this.rightMenu.updateRightMenuDisable();
      // DOM操作隐藏 “帮助” and “显示页面地址” 、加分隔线
      throttleOfPart(this.rightMenu.hideRightMenuUseless, 30); // 使用节流函数
   });


   /** *****  移动文件/文件夹相关  ****** */
   @observable moveFilesData = {
      ref: null,
   };
   @action setMoveFilesData = (newData = {}) => {
      Object.keys(newData).forEach((i) => {
         this.moveFilesData[i] = newData[i];
      });
   };


   /** *****   查看分享对象 模态框相关   ****** */
   @observable lookTarget = {
      visible: false,
      searchVal: '',
      data: [],
      selectedKeys: [],
      checkboxValue: '0',
   };

   // todo 调用API获取数据
   @action getLookTargetData = () => {
      this.lookTarget.data = [
         {
            type: 'person',
            id: '1',
            img: '',
            name: 'Bug开发',
            sex: '0',
            desc1: '系统集成组/EBU事业本部',
            desc2: '分享时间：2019-10-21 09:41:30',
         },
         {
            type: 'person',
            id: '2',
            img: '',
            name: '宕机专家',
            sex: '0',
            desc1: '工作流程组/EBU事业本部',
            desc2: '分享时间：2019-10-21 09:42:50',
         },
         {
            type: 'group',
            id: '3',
            img: '',
            name: 'Error狂欢组',
            sex: '',
            desc1: '9人',
            desc2: '分享时间：2019-10-21 09:42:50',
         },
      ];
   };

   // 修改 lookTarget 数据统一接口
   @action setLookTarget = (newData = {}) => {
      Object.keys(newData).forEach((i) => {
         this.lookTarget[i] = newData[i];
      });
   };

   // 监控分享对象的 selectedKeys，改变顶部checkbox的值
   monitorShareTargetSelect = autorun(() => {
      const selectLen = this.lookTarget.selectedKeys.length;
      const dataLen = this.getLookTargetDataLen();
      selectLen === 0 && (this.lookTarget.checkboxValue = '0');
      selectLen > 0 && selectLen < dataLen && (this.lookTarget.checkboxValue = '2');
      selectLen > 0 && selectLen === dataLen && (this.lookTarget.checkboxValue = '1');
   });
   @action getLookTargetDataLen = () => this.lookTarget.data.length;


   /** ******  传输框组件  ******* */
   @observable transportData = {
      ref: null,
   };
   // 赋值ref
   @action setTransportData = (newData = {}) => {
      Object.keys(newData).forEach((i) => {
         this.transportData[i] = newData[i];
      });
   };


   /** ******  分享相关  ******* */
   @observable shareData = {
      visible: false,
      keys: '',
   };
   @action setShareData = (newData = {}) => {
      const items = Object.keys(newData);
      let keys = '';
      items.forEach((i) => {
         this.shareData[i] = newData[i];
      });
      items.includes('visible') && !items.includes('keys') && (keys = toJS(this.fileSystem.tableStore.selectedRowKeys).join(','));
      this.shareData.keys = keys;
   };
}

export default NetDisk;
